<template>
  <el-dialog
    :title="title"
    :width="width"
    top="50px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="isVisible"
  >
    <el-form ref="form" :model="user" :rules="rules" label-position="right" label-width="100px">

      <el-form-item :label="$t('table.user.username')" prop="doctorName">
        <el-input v-model="user.doctorName" />
      </el-form-item>
      <el-form-item :label="$t('table.user.mobile')" prop="mobile">
        <el-input v-model="user.mobile" oninput="value=value.replace(/[^\d]/g,'')" maxlength="11" />
      </el-form-item>
      <el-form-item label="机构" prop="organizationId">
        <el-select v-model="user.organizationId" value="" placeholder="" style="width:100%" @change="organizationIdFun">
          <el-option v-for="item in deptTree" :key="item.id" :value="item.id" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="科室" prop="clinicId">
        <el-select v-model="user.clinicId" value="" @change="clinicIdFun" placeholder="" style="width:100%">
          <el-option v-for="item in clinicIdLIst" :key="item.id" :value="item.id" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('table.user.sex')" prop="gender">
        <el-select v-model="user.gender" value="" placeholder="" style="width:100%">
          <el-option value="1" :label="$t('common.sex.male') " />
          <el-option value="2" :label="$t('common.sex.female') " />
          <el-option value="3" :label="$t('common.sex.secret') " />
        </el-select>
      </el-form-item>
      <el-form-item label="工号">
        <el-input v-model="user.doctorId" readonly />
      </el-form-item>
      <el-form-item label="职称">
        <el-input v-model="user.ranks" />
      </el-form-item>

      <el-form-item label="状态">
        <!-- <el-input v-model="user.status" readonly="true" /> -->
        <span v-if="user.status == 0">未审核</span>
        <span v-if="user.status == 1">已审核</span>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" plain :loading="buttonLoading" @click="isVisible = false">
        {{ $t('common.cancel') }}
      </el-button>
      <el-button type="primary" plain :loading="buttonLoading" @click="submitForm">
        {{ $t('common.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
// 校验规则 使用框架自带的校验方式（必引入）
import {
  validMobile
} from '@/utils/my-validate'
  // 使用树结构的情况下（必须引入）
// import Treeselect from '@riophae/vue-treeselect'
// 使用树结构的情况下（必须引入）
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'UserEdit',
  components: {
    // Treeselect
  },
  props: {
    // 控制弹窗显示隐藏 （默认即可）
    dialogVisible: {
      type: Boolean,
      default: false
    },
    // 弹窗的标题（默认）
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 暂时不用
      initFlag: false,
      // 初始化数据（默认  （如果里面字段需要修改可对应修改））
      user: this.initUser(),
      // button加载动画（默认不可更改）
      buttonLoading: false,
      screenWidth: 0,
      width: this.initWidth(),
      // 部门
      depts: [],
      // 角色
      roles: [],
      // 树形接口数组
      deptTree: [],
      // 科室的
      clinicIdLIst: [],
      // 校验的方法 （里面对象名字对应上面的prop 对应的值）
      rules: {
        doctorName: [{
          required: true,
          message: this.$t('rules.require'),
          trigger: 'blur'
        }
        ],
        mobile: {
          validator: (rule, value, callback) => {
            if (value !== '' && !validMobile(value)) {
              callback(this.$t('rules.mobile'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        },
        gender: {
          required: true,
          message: this.$t('rules.require'),
          trigger: 'change'
        }
      }
    }
  },
  computed: {
    // 计算弹窗变化
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
        this.reset()
      }
    }
  },
  created() {
    this.initDept()
    this.initRoles()
    this.organizationIdFun();
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.width = this.initWidth()
      })()
    }
  },
  methods: {

    initUser() {
      // 初始化数据  里面的名称可以自定义修改对到表单里面的字段
      return {
        'clinicId': '',
        'clinicName': '',
        'createAt': '',
        'createBy': '',
        'deleteAt': 0,
        'doctorId': '',
        'doctorName': '',
        'email': '',
        'gender': '',
        'id': '',
        'idNo': '',
        'mobile': '',
        'organization': '',
        'organizationId': '',
        'rank': 0,
        'remark': '',
        'smsCode': '',
        'status': 0,
        'udpateAt': '',
        'updateBy': '',
        'wxUserId': ''
      }
    },
    // 根据页面宽度控制弹窗的宽度（不可删除默认）
    initWidth() {
      this.screenWidth = document.body.clientWidth
      if (this.screenWidth < 991) {
        return '90%'
      } else if (this.screenWidth < 1400) {
        return '45%'
      } else {
        return '800px'
      }
    },
    // clinicIdFun 配合科室名称
    clinicIdFun(){
      this.user.clinicName = "";
      for(let i=0;i<this.clinicIdLIst.length;i++){
        if(this.clinicIdLIst[i].id == this.user.clinicId){
          this.user.clinicName = this.clinicIdLIst[i].label;
          break
        }else{
          this.user.clinicName = "";
          break
        }
      }
    },
    // organizationIdFun  机构
    organizationIdFun() {
      // clinicIdLIst
      this.clinicIdLIst = []
      for (let i = 0; i < this.deptTree.length; i++) {
        if (this.deptTree[i].id == this.user.organizationId) {
          this.user.organization = this.deptTree[i].label;
          if (this.deptTree[i].children) {
            this.clinicIdLIst = this.deptTree[i].children
          } else {
            this.user.clinicId = ''
            this.clinicIdLIst = []
          }
        }
      };
      this.clinicIdFun();
      console.log(this.clinicIdLIst)
    },
    // 获取弹窗部门树方法  （可更换接口）
    initDept() {
      this.$get('system/dept').then((r) => {
        this.depts = r.data.data.rows
        this.deptTree = this.depts
      }).catch((error) => {
        console.error(error)
        this.$message({
          message: this.$t('tips.getDataFail'),
          type: 'error'
        })
      })
    },
    // 清空选择
    resetDeptTree() {
      // this.$refs.deptTree.setCheckedKeys([])
    },
    // 获取部门的下拉数据  赋值给roles
    initRoles() {
      this.$get('system/role/options').then((r) => {
        this.roles = r.data.data
      }).catch((error) => {
        console.error(error)
        this.$message({
          message: this.$t('tips.getDataFail'),
          type: 'error'
        })
      })
    },

    setUser(val) {
      this.user = {
        ...val
      }
      this.organizationIdFun()
    },
    // 关闭抛给父文件关闭弹窗的方法
    close() {
      this.$emit('close')
    },
    // 提交方法
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          const data = {
            ...this.user
          }
          console.log(data)
          data.createAt = null
          this.$put('referral/doctor', data).then(() => {
            this.buttonLoading = false
            this.isVisible = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.$emit('success')
          })
        } else {
          return false
        }
      })
    },
    // 重置
    reset() {
      // 先清除校验，再清除表单，不然有奇怪的bug
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.user = this.initUser()
      this.resetDeptTree()
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
